<?php
declare(strict_types=1);

namespace App\Bootstrap;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Str;
use support\Db;
use support\Log;
use Webman\Bootstrap;

class SqlDebug implements Bootstrap {
    public static function start ($worker): void {
        if (config('database.debug', true)) {
            Db::connection()->listen(function (QueryExecuted $queryExecuted) {
                if (isset($queryExecuted->sql) and $queryExecuted->sql !== "select 1") {
                    $bindings = [];
                    if ($queryExecuted->bindings) {
                        foreach ($queryExecuted->bindings as $v) {
                            if (is_numeric($v)) {
                                $bindings[] = $v;
                            } else {
                                $bindings[] = '"' . strval($v) . '"';
                            }
                        }
                    }
                    $sql = Str::replaceArray('?', $bindings, $queryExecuted->sql);
                    Log::debug("[{$queryExecuted->time} ms] {$sql}");
                }
            });
        }

    }
}